#include <stdio.h>
#include <tchar.h>
#include <iostream>

#include "snake.h"

snake::snake(void)
{
	length = 0;
	changespeed = false;
}

snake::snake(int posx,int posy,world* w)
{
	changespeed = false;
	length = 1;
	direction = 'd';
	sc = 0;

	if(w->map[posx][posy]->gettype()==blank)
	{
		w->map[posx][posy]->settype(head);
		sks.push_back(w->map[posx][posy]);
	}
	//snake_head->setnote(posx,posy,head);
}

bool snake::move(world* w)
{
	int x = sks.front()->getx();
	int y = sks.front()->gety();
	int nextx;
	int nexty;

	if(direction == 'd')
	{
		nextx = x + 1;
		nexty = y;
	}
	else if(direction == 's')
	{
		nextx = x;
		nexty = y - 1;
	}
	else if(direction == 'a')
	{
		nextx = x - 1;
		nexty = y;
	}
	else if(direction == 'w')
	{
		nextx = x;
		nexty = y + 1;
	}


	if(w->map[nextx][nexty]->gettype()==blank)
	{
		changespeed = false;
		w->map[nextx][nexty]->settype(head);
		//snake_head->setnote(nextx,nexty,head);
		std::list<note*>::iterator it;
		for(it = sks.begin();it!= sks.end();it++)
		{
			w->map[(*it)->getx()][(*it)->gety()]->settype(body);
		}
		sks.push_front(w->map[nextx][nexty]);
		w->map[sks.back()->getx()][sks.back()->gety()]->settype(blank);
		sks.pop_back();
	}
	else if(w->map[nextx][nexty]->gettype()==foods)
	{
		changespeed = true;
		w->map[nextx][nexty]->settype(head);
		//snake_head->setnote(nextx,nexty,head);
		w->map[x][y]->settype(body);
		sks.push_front(w->map[nextx][nexty]);
		w->putfood(w);
		sc++;
	}
	else if(w->map[nextx][nexty]->gettype()==traps)
	{
		changespeed = true;
		w->map[nextx][nexty]->settype(blank);

		std::list<note*>::iterator it;
		for(it = sks.begin();it!= sks.end();it++)
		{
			if(it != sks.begin())
			{
				w->map[(*it)->getx()][(*it)->gety()]->settype(body);
			}
		}
		w->map[sks.back()->getx()][sks.back()->gety()]->settype(blank);
		sks.pop_back();
		w->puttrap(w);
		if(sks.size() == 0)
		{
			return false;
		}
	}
	else
	{
		return false;
	}



	if(direction == 'd')
	{
		sks.front()->getSprite()->setRotation(0);
	}
	else if(direction == 's')
	{
		sks.front()->getSprite()->setRotation(90);
	}
	else if(direction == 'a')
	{
		sks.front()->getSprite()->setRotation(180);
	}
	else if(direction == 'w')
	{
		sks.front()->getSprite()->setRotation(-90);
	}
	return true;
}

void snake::setdr(char d)
{
	direction = d;
}

char snake::getdr()
{
	return direction;
}

int snake::getsc()
{
	return sc;
}
int snake::getlength()
{
	return sks.size();
}
bool snake::changeSpeed()
{
	return changespeed;
}
void snake::resetchangeSpeed()
{
	changespeed = false;
}

note snake::getheadPoint()
{
	return *sks.front();
}

snake::~snake(void)
{
}
